package com.javaex.book.utils;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON工具类
 *
 * @author 黄星琦
 * @Date 2022年1月17日
 */
public class JsonUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
	protected static ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * 将JSON字符串转为对象
	 * @param <T> 目标对象类型
	 * @param json JSON字符串
	 * @param clazz 目标对象类
	 * @return 对象实例
	 */
	public static <T> T parse(String json, Class<T> clazz) {
		T obj = null;
		try {
			obj = objectMapper.readValue(json, clazz);
		} catch (Exception e) {
			logger.error("JSON字符串解析失败", e);
		} 
		return obj;
	}
	
	public static Map<String, Object> parseToMap(String json) {
		Map<String, Object> map = null;
		try {
			map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
		} catch (Exception e) {
			logger.error("JSON字符串解析失败", e);
		}
		return map;
	}
	
	/**
	 * 将JSON字符串转为List集合
	 * @param <T> 目标对象类型
	 * @param json JSON字符串
	 * @return List集合
	 */
	public static <T> List<T> parseToList(String json) {
		List<T> list = null;
		try {
			objectMapper.readValue(json, new TypeReference<List<T>>() {});
		} catch (Exception e) {
			logger.error("JSON字符串解析失败", e);
		}
		return list;
	}
	
	/**
	 * 将对象转为JSON字符串
	 * @param obj 数据
	 * @return JSON字符串
	 */
	public static String stringify(Object obj) {
		String json = null;
		try {
			json = objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			logger.error("JSON字符串解析失败", e);
		}
		return json;
	}
}
